<?php
class languages extends CWidget
{
	public function init()
	{
		parent::init();
	}
	public function run()
	{
		$curr_language  = Yii::app()->language;
		$Languages = Yii::app()->params['languages'];
		$langs = array();
		foreach($Languages as $key => $value){
			$langs[$key] = array('name'=>$value,
								 'url' =>$this->GetRounterUrlLang($key)
								);
		}
		$this->render('default', array('curr_language'=>$curr_language, 'lang_url'	=>	$langs));
	}
	private function GetRounterUrlLang($lang)
	{
		/*$hrefVars = '';
		$href= "index.php";
		$queryString = $_SERVER['QUERY_STRING'];
		if( !empty($queryString) ) {
				$vars = explode( "&", $queryString );
				if( count($vars) > 0 && $queryString) {
					foreach ($vars as $var) {
						if( preg_match('/=/i', $var ) ) {
							list($key, $value) = explode( "=", $var);
							if( $key != "lang" ) {
								if( $hrefVars != "" ) {
									$hrefVars .= "&amp;";
								}
								// ignore mosmsg to ensure it is visible in frontend
								if( $key != 'mosmsg' ) {
									$hrefVars .= "$key=$value";
								}
							}
						}
					}
				}
			}
			if( $hrefVars != "" ) {
				$href .= '?' .$hrefVars;
			}

			$ulang = 'lang='.$lang;
			if( $hrefVars == '' ) {
				$href .= '?' . $ulang;
			} else {
				$href .= '&amp;' . $ulang;
			}
		return $href;
		*/
		$queryString = $_SERVER['QUERY_STRING'];
		$url_parse =  array();
		$url='';
		if(strpos($queryString, '&')!==false){
			$url_explode = explode('&', $queryString);
			foreach($url_explode as $key => $value){
				if(preg_match('/=/i', $value )){
					list($key1, $val1) = explode( "=", $value);
					$url_parse[$key1] = $val1;
				}
			}
		}else{ 
			if( preg_match('/=/i', $queryString ) ) {
				list($key, $value) = explode( "=", $queryString);
				$url_parse[$key] = $value;
			}
		}
		if(count($url_parse)>0){
			if(key_exists('lang', $url_parse)==false && $lang!=Yii::app()->params['language_default']){
				$url_parse['lang'] = $lang;
			}else{
				if($lang==Yii::app()->params['language_default']){
					unset($url_parse['lang']);
				}else{
					$url_parse['lang'] = $lang;
				}
				}
			$r = $url_parse['r'];
			unset($url_parse['r']);
			$url = Yii::app()->createUrl("$r", $url_parse);
		}
		return $url;
	}
}